package sfeir.ergosum;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SendMailActivity extends Activity implements OnClickListener {

    String url;
    String alias;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sendmail);

        Button button = (Button) findViewById(R.id.sendbutton);
        button.setOnClickListener(this);

        TextView tv = (TextView) findViewById(R.id.contactname);

        Intent i = getIntent();
        if (i.getExtras().getString("CONTACT_URL") != null) {
            alias = i.getExtras().getString("CONTACT_ALIAS");
            
            url = buildLink(i.getExtras().getString("CONTACT_URL"), alias);
            
            tv.setText(alias);
        }

    }

    private String buildLink(String url, String alias) {
        String link = "ergo:";
        if (url.matches("(\\w|-)+")) {
            link += "//spreadsheets.google.com/ccc?key=" + url;
        }
        else {
            Uri uri = Uri.parse(link);
            link += uri.getSchemeSpecificPart();
        }
        link += "#" + alias;
        return link;
    }

    @Override
    public void onClick(View v) {
        EditText et = (EditText) findViewById(R.id.emailfield);

        String[] mailto = { et.getText().toString() };
        // Create a new Intent to send messages
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setData(Uri.parse("mailto:" + mailto));
        // Add attributes to the intent
        sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
        String subject = getString(R.string.mail_subject, alias);
        Log.d("ErgoSum", subject);
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        String text = getString(R.string.mail_text, alias, url);
        Log.d("ErgoSum", text);
        sendIntent.putExtra(Intent.EXTRA_TEXT, text);
        sendIntent.setType("text/plain");
        startActivity(Intent.createChooser(sendIntent, "Choix du client mail"));
    }
}
